using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Collections;


namespace MapaMovil
{
    class CargaMasiva
    {
        /*   public static void Main(string[] args)
       {
           string m_strFileName = args[0];
           generateXMLs(m_strFileName, args[1],args[2]);
       }*/
        public static void generateXMLs(string m_strFileName, string node, string name, string type, Mapa m,string path)
        {
            //MessageBox.Show(m_strFileName + "-" + node + "-" + name);
            Cursor.Current = Cursors.WaitCursor;
            XmlTextReader piReader = null;
            piReader = new XmlTextReader(m_strFileName);

            bool work = piReader.Read();
            while (work)
            {
                if (piReader.NodeType == XmlNodeType.Element)
                {
                    //MessageBox.Show(piReader.Name);
                    if (piReader.Name.Equals(node))
                    {
                        String filename = "";
                        String filetype = "";
                        //Console.WriteLine("Entre");
                        StringWriter sw = new StringWriter();
                        XmlTextWriter xmlw = new XmlTextWriter(sw);
                        xmlw.Formatting = Formatting.Indented;
                        xmlw.Indentation = 5;
                        xmlw.IndentChar = ' ';
                        //Console.WriteLine(piReader.G);
                        int depth = piReader.Depth;
                        int ldepth = depth;
                        int cdepth;
                        bool read = true;
                        piReader.Read();
                        while (piReader.Depth > depth)
                        {
                            if (piReader.NodeType == XmlNodeType.Element)
                            {
                                read = true;
                                cdepth = piReader.Depth;
                                //Console.WriteLine("ad:" + piReader.Depth + "-" + ldepth);
                                //Console.WriteLine("elemetno:" + piReader.Name);
                                if (cdepth <= ldepth)
                                {
                                    //Console.WriteLine("ad:" + piReader.Depth + "-" + ldepth);
                                    for (int i = cdepth; i <= ldepth; i++)
                                    {
                                        //Console.WriteLine("cerrando:" + i);
                                        xmlw.WriteEndElement();
                                    }
                                }
                                //MessageBox.Show("Agregando:" + piReader.Name);
                                String node_name = piReader.Name;
                                xmlw.WriteStartElement("", node_name, "");
                                String val = piReader.ReadString().Trim();
                                if (val.Equals("")) read = false;
                                if (node_name.Equals(name)) filename = val;
                                if (node_name.Equals(type)) filetype = val;
                                xmlw.WriteString(val);

                                ldepth = cdepth;
                                //Console.WriteLine("depth:" + ldepth);
                            }
                            if (read) work = piReader.Read();

                        }
                        //Console.WriteLine("ad:" + piReader.Depth + "-" + ldepth);
                        cdepth = piReader.Depth;
                        if (cdepth <= ldepth)
                        {
                            //Console.WriteLine("ad:" + piReader.Depth + "-" + ldepth);
                            for (int i = cdepth; i < ldepth; i++)
                            {
                                //Console.WriteLine("cerrando:" + i);
                                xmlw.WriteEndElement();
                            }
                        }
                        xmlw.Flush();
                        //MessageBox.Show(sw.ToString());
                        if (node.Equals("Area")) filetype = "";
                        writeXMLFile("<" + node + ">" + sw.ToString() + "</" + node + ">", filename, filetype,m,path, name == "Area" );
                    }
                    else
                    {
                        work = piReader.Read();
                    }
                }
                else
                {
                    work = piReader.Read();
                }
            }
            Cursor.Current = Cursors.Default;
            if (node.Equals("Area")) MessageBox.Show("Areas cargadas");
            else if (node.Equals("POI")) MessageBox.Show("Puntos de Interes cargados");
        }
        public static void writeXMLFile(String xml, String file, String folder, Mapa m, string path, bool isArea)
        {
            // String path = "\\MapaMovil\\POI\\";
            //MessageBox.Show(path + folder + file + ".xml" + ":" + xml);
            String dir = "";
            if(!isArea)
                dir = path +"\\"+ folder + "\\";
            else
                dir = path + "\\";

            //check if the directory exists
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
                loadPuntos(folder, path + "\\" + folder, m);
            }
            
            StreamWriter sw = new StreamWriter(dir + file + ".xml");
            sw.Write(xml);
            sw.Close();
            
            /*
             if (!isInConfigFile(folder, (GrupoPuntoDeInteres[])m.gruposPDI.ToArray()))
            {
                addCategorie(folder, folder + ".png", path + folder);
                loadPuntos(folder, path +"\\"+ folder, m);
            }
            */
            if (isArea)
            {
                m.grupoADI.agregarAreaDeInteres(m.grupoADI.loadADIXml(dir + file + ".xml"), false);
                m.updatePolygonList(m.getNW(), m.grupoADI);
            }
        }
        /*agrega un nuevo tipo de punto al conjunto*/
        public static void loadPuntos(String nombre, String path, Mapa m)
        {
            m.addPDI(new GrupoPuntoDeInteres(nombre, path));
        }
        /*AGREGA UNA NUEVA CATEGORIA AL ARCHIVO CONFIG.XML*/
        public static void addCategorie(String name, String icon, String path)
        {
            String pathConfig = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            pathConfig += @"\config.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(pathConfig);
            XmlElement newElem = doc.CreateElement("POI");
            newElem.InnerXml = "<nombre></nombre><icono></icono><path></path>";
            newElem["nombre"].InnerText = name;
            newElem["icono"].InnerText = icon;
            newElem["path"].InnerText = path;
            XmlNode pois = doc.DocumentElement.SelectSingleNode("descendant::POIs");
            pois.AppendChild(newElem);


            XmlTextWriter wrtr = new XmlTextWriter(pathConfig, Encoding.UTF8);
            wrtr.Formatting = Formatting.Indented;
            wrtr.Indentation = 5;
            wrtr.IndentChar = ' ';

            doc.WriteTo(wrtr);
            wrtr.Close();
        }
        /*devuelve si ya estaba en las categorias o no, aun no se que hacer con las areas*/
        public static bool isInConfigFile(String nombre, GrupoPuntoDeInteres[] gpdi)
        {
            bool found = false;
            /*no se que hacer con las areas aun*/
            if (nombre.StartsWith("area\\")) found = true;
            else
            {
                for (int i = 0; i < gpdi.Length; i++)
                {
                    if (gpdi[i].Nombre.Equals(nombre)) found = true;
                }
            }
            return found;
        }
    }
}